import axios from 'axios';
// import { useUserStore } from '@/stores';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { baseURL_dev } from '@/config/baseURL';

const instance = axios.create({
    // 1.基础地址，超时时间
    baseURL: baseURL_dev,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
instance.interceptors.request.use((config) => {
    // 2.携带token
    // const userStore = useUserStore();
    // if (userStore.token) {
    //     config.headers.Authorization = userStore.token
    // }
    return config;

})

// 响应拦截器
instance.interceptors.response.use((res) => {
    // 3.摘取核心响应数据
    if (res.data.code === 0) {
        return res
    }
    // 4.处理业务失败
    ElMessage.error(res.data.message || '服务异常');
    return Promise.reject(res.data);
},
    (err) => {
        // 5.处理401错误
        // 特殊错误 => 401 权限不足 或 token过期 => 拦截到登录
        if (err.response?.status === 401) {
            router.push('/login');
        }
        // 默认错误 => 只要给提示
        ElMessage.error(err.response.data.message || '服务异常');
        return Promise.reject(err)
    }
)

// get请求方法
export const $get = async (url: string, params: object = {}) => {
    let { data } = await instance.get(url, { params });
    return data;
}

// post请求方法
export const $post = async (url: string, params: object = {}) => {
    let { data } = await instance.post(url, params);
    return data;
}

// delete请求方法
export const $delete = async (url: string, params: object = {}) => {
    let { data } = await instance.delete(url, { params });
    return data;
}

// put请求方法
export const $put = async (url: string, params: object = {}) => {
    let { data } = await instance.put(url, params);
    return data;
}

export default instance;
export { baseURL_dev }